package top.tagao.multithread_04_sync;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/29 21:42
 * 使用同步代码块解决实现Runnable接口的方式的线程安全问题
 * <p>
 * 例子：创建三个窗口卖票，总票数为100张.使用实现Runnable接口的方式
 * <p>
 * 补充：在实现Runnable接口创建多线程的方式中，我们可以考虑使用this充当同步监视器。
 */
public class Sync_02_block {
    public static void main(String[] args) {
        WinRunnable02 winRunnable02 = new WinRunnable02();
        Thread thread1 = new Thread(winRunnable02);
        Thread thread2 = new Thread(winRunnable02);
        Thread thread3 = new Thread(winRunnable02);
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class WinRunnable02 implements Runnable {
    private int ticket = 100;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":卖票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
